<template>
  <div v-if="open" class="fixed inset-0 bg-black/40 grid place-items-center p-4 z-50">
    <div class="card w-full max-w-lg">
      <div class="text-lg font-semibold mb-2">{{ isEditMode ? '编辑睡眠记录' : '记录睡眠' }}</div>
      <form class="space-y-3" @submit.prevent="save">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
          <label class="block">
            <span class="text-sm">开始时间</span>
            <input class="input mt-1" type="datetime-local" v-model="startLocal" />
          </label>
          <label class="block">
            <span class="text-sm">结束时间（可空）</span>
            <input class="input mt-1" type="datetime-local" v-model="endLocal" />
          </label>
        </div>
        <label class="block">
          <span class="text-sm">备注</span>
          <textarea class="input mt-1" rows="3" placeholder="可输入备注...（可选）" v-model="note" />
        </label>
        <div class="flex justify-end gap-2">
          <button type="button" class="px-4 py-2 rounded bg-bg" @click="emit('update:open', false)">取消</button>
          <button class="btn-primary" type="submit">保存</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useUserStore } from '../stores/user';
import { API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function createSleep(payload: any) {
  const token = localStorage.getItem('auth_token');
  console.log('SleepModal createSleep - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/sleep`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function updateSleep(payload: any) {
  const token = localStorage.getItem('auth_token');
  console.log('SleepModal updateSleep - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/sleep/${payload.id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

const props = defineProps<{ 
  open: boolean;
  editData?: any; // 编辑时的数据
}>();
const emit = defineEmits<{ 
  (e: 'update:open', v: boolean): void;
  (e: 'saved'): void;
}>();
const userStore = useUserStore();

const startLocal = ref<string>('');
const endLocal = ref<string>('');
const note = ref<string>('');
const isEditMode = computed(() => !!props.editData);

watch(
  () => props.open,
  (v) => {
    if (v) {
      if (props.editData) {
        // 编辑模式：填充现有数据
        const startTime = new Date(props.editData.sleepStart);
        startLocal.value = new Date(startTime.getTime() - startTime.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        if (props.editData.sleepEnd) {
          const endTime = new Date(props.editData.sleepEnd);
          endLocal.value = new Date(endTime.getTime() - endTime.getTimezoneOffset() * 60000)
            .toISOString()
            .slice(0, 16);
        } else {
          endLocal.value = '';
        }
        note.value = props.editData.note || '';
      } else {
        // 新建模式：使用当前时间
        const now = new Date();
        startLocal.value = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        endLocal.value = '';
        note.value = '';
      }
    }
  }
);

async function save() {
  if (!userStore.currentBabyId) {
    alert('请先选择宝宝');
    return;
  }

  if (!startLocal.value) {
    alert('请填写开始时间');
    return;
  }

  try {
    const startTime = new Date(startLocal.value).toISOString();
    const endTime = endLocal.value ? new Date(endLocal.value).toISOString() : undefined;

    if (isEditMode.value) {
      // 编辑模式：调用更新API
      await updateSleep({
        id: props.editData.id,
        babyId: userStore.currentBabyId,
        startTime,
        endTime,
        note: note.value || undefined
      });
    } else {
      // 新建模式：调用创建API
      await createSleep({
        babyId: userStore.currentBabyId,
        startTime,
        endTime,
        note: note.value || undefined
      });
    }

    emit('saved');
    emit('update:open', false);
  } catch (error) {
    console.error('保存睡眠记录失败:', error);
    alert('保存失败，请重试');
  }
}
</script>

<style scoped></style>